using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;

namespace Nirvana.AB
{
    public class AssetBundleUtils
    {
        private static Dictionary<string, AssetTarget> _assetPath2TargetDic = new Dictionary<string, AssetTarget>();
        private static HashSet<string> _allShaders = new HashSet<string>();

        /// <summary>
        /// 全部的资源
        /// </summary>
        /// <returns></returns>
        public static List<AssetTarget> GetAllAssets()
        {
            return _assetPath2TargetDic.Values.ToList();
        }

        /// <summary>
        /// 获取有多个父依赖的资源
        /// </summary>
        /// <returns></returns>
        public static List<AssetTarget> GetCombineAsset()
        {
            var all = GetAllAssets();
            var del = all.Where(assetTarget => assetTarget.exportAssetType != ExportAssetType.Root && assetTarget.dependParentSet.Count == 1).ToList();
            return all.Except(del).ToList();
        }
        
        /// <summary>
        /// 生成AssetTarget资源，并缓存
        /// </summary>
        /// <param name="assetPath"></param>
        /// <returns></returns>
        public static AssetTarget Load(string assetPath)
        {
            AssetTarget target = null;
            if (!_assetPath2TargetDic.TryGetValue(assetPath, out target) && !IsShaderAsset(assetPath))
            {
                target = new AssetTarget(assetPath);
                _assetPath2TargetDic.Add(assetPath, target);
            }

            return target;
        }

        /// <summary>
        /// 检查是否是Shader文件
        /// </summary>
        /// <param name="assetPath"></param>
        /// <returns></returns>
        public static bool IsShaderAsset(string assetPath)
        {
            var extension = Path.GetExtension(assetPath);
            if (extension == ".Shader")
            {
                if (!_allShaders.Contains(assetPath))
                {
                    _allShaders.Add(assetPath);
                }

                return true;
            }

            if (extension == ".cginc")
            {
                return true;
            }

            return false;
        }

        /// <summary>
        /// 转换成AB形式的名字
        /// 如果是场景文件则直接取场景名字(带后缀.unity)
        /// 如果是在资源根路径中的截取后续的内容并转小写
        /// </summary>
        /// <param name="assetPath"></param>
        /// <returns></returns>
        public static string ToABName(string assetPath)
        {
            assetPath = assetPath.Replace(" ", string.Empty);
            if (assetPath.IndexOf(BundleUtils.AssetsRoot, StringComparison.Ordinal) != -1)
            {
                return assetPath.Substring(assetPath.IndexOf(BundleUtils.AssetsRoot, StringComparison.Ordinal) + BundleUtils.AssetsRoot.Length).ToLower();
            }

            return assetPath.ToLower();
        }
    }
}
